//维修记录
import React, { Component } from 'react';
import { Table, Form, Card, Tabs } from 'antd';
import '@/assets/css/settings';
import BasicForm from "../../components_yyr/common/basicForm";
import BasicDrawers from "../../components_yyr/common/basicDrawers";
import { FileDown } from "../../components_yyr/commponent/File";
import Paging from "../../components_yyr/commponent/Paging";
import { withRouter } from 'react-router-dom';
import BasicConfirm from "../../components_yyr/common/basicConfirm";
import * as Utils from '../../utils_yyr/action';
import { euqApplicationName, lotAuth, lotAuth2 } from '../../config';
const { TabPane } = Tabs;
class App extends Component {
	state = {
		loading: false, //加载中...
		dataSource: [], //数据源
		drawerVisible: false,//新增修改抽屉的显示与隐藏
		chooseData: {},
		drawerTitle: '',
		total: 0,
		formValues: {},
		cityData: [],
		mainFactoryList: [],
		selectedData: [],
		selectedKeys: [],
		DepartmentList:[]
	};
	componentDidMount() {
		this.fetch({
			pageNum: 1,
			pageSize: 10,
			userId:localStorage.getItem('userId')
		});
		this.queryTreeDepartment();
	}
	//初始化加载数据
	fetch = (data) => {
		console.log(data)
		let str = ''
		for(var key in data){
			if(data[key] || data[key] == 0){
				str += `&${key}=${data[key]}`
			}
		}
		this.setState({ loading: true })
		this.get(euqApplicationName + '/equipmentMaintenanceRecord/findEquipmentMaintenanceRecordList?'+str).then(res => {
			this.setState({
				loading: false,
				dataSource: res.data.data,
				total:res.data.total,
				formValues:data
			});
		})
	}

	//表单查询
	filterSubmit = (values) => {
		console.log("表单查询=====", values)
		if(values.startTime_endTime && values.startTime_endTime.length==2){
			values.startTime = Utils.getDate(values.startTime_endTime[0]) + ' 00:00:00'
			values.endTime = Utils.getDate(values.startTime_endTime[1]) + ' 23:59:59'
		}
		values.pageNum = this.state.formValues.pageNum;
		values.pageSize = this.state.formValues.pageSize;
		// values.userId = localStorage.getItem('userId');
		this.fetch(values);
	};

	// 表格删除
	handleConfirm = (value, api, chooseData) => {
		console.log(this.state.selectedData)
			let str = ''
			for(var item of this.state.selectedData){
				str += item.id + ','
			}
		this.get(`${euqApplicationName}/equipmentMaintenanceRecord/deleteEquipmentMaintenanceRecord/${str.slice(0, str.length - 1)}`).then(res => {
				this.success();
				this.fetch({ ...this.state.formValues });
				this.setState({selectedKeys:[],selectedData:[]})
			});

	}

	// 表格打印
	handlePrinting = (type, data) => {
		console.log("打印=====")
	}
// 部门查询
	
	queryTreeDepartment = () => {
		// this.get(lotAuth + '/department/queryTreeDepartment').then(res => {
			this.get(lotAuth2 + '/department/queryTreeDepartment').then(res => {
			this.setState({
				DepartmentList : res.data
			});
		})
	}

	formList = () => {
		const formList = [
			{ type: "TIMEFRAME", label: "维修时间", field: "startTime_endTime", },
			{ type: "INPUT", label: "维修单号", field: "repairOrder" },
			{
				type: "SELECT", label: "使用部门", field: "dept", name: 'name',
				list: this.state.DepartmentList, valueField: 'id'
			},
			// { type: "INPUT", label: "快速查询", field: "route" },

		]
		return formList;
	};
	drawerFormList = data => {
		const { mainFactoryList } = this.state;
		const drawerFormList = [
			{ type: 'TITLE', label: '基本信息' },
			{ type: "INPUT", label: "维修单号", field: "factoryName", initialValue: data.factoryName, list: mainFactoryList },
			{ type: "INPUT", label: "设备名称", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "INPUT", label: "设备编码", field: "route", initialValue: data.route },
			{ type: "INPUT", label: "规格型号", field: "ggxh", initialValue: data.ggxh },
			{ type: "INPUT", label: "试用部门", field: "harborTwoHundredPrice", initialValue: data.harborTwoHundredPrice },
			{ type: "INPUT", label: "设备位置", field: "sbwz", initialValue: data.sbwz },

			{ type: 'TITLE', label: '故障信息' },
			{ type: "INPUT", label: "报修单号", field: "route", initialValue: data.route },
			{ type: "INPUT", label: "发生时间", field: "tiTime", initialValue: data.tiTime, list: mainFactoryList },
			{ type: "INPUT", label: "报修时间", field: "baoxiuTime", initialValue: data.baoxiuTime },
			{ type: "INPUT", label: "报修人", field: "sqr", initialValue: data.sqr },
			{ type: "SELECT", label: "故障部位", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TREESELECT", label: "故障类别", field: "remark5s", initialValue: data.remark5s, name: 'value', valueField: 'value', list: mainFactoryList.remark5s },
			{ type: "SELECT", label: "故障等级", field: "wxlevel", initialValue: data.wxlevel, name: 'value', valueField: 'value', list: mainFactoryList.wxlevel },
			{ type: "TEXTAREA", label: "故障语言", field: "remarks", initialValue: data.remarks },

			{ type: 'TITLE', label: '处理情况' },
			{ type: "SELECT", label: "故障原因", field: "gzyy", initialValue: data.gzyy, name: 'value', valueField: 'value', list: mainFactoryList.gzyy },
			{ type: "SELECT", label: "维修组", field: "wxGroup", initialValue: data.wxGroup, name: 'value', valueField: 'value', list: mainFactoryList.wxGroup },
			{ type: "INPUT", label: "维修状态", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "SELECT", label: "维修级别", field: "wxjb", initialValue: data.wxjb, name: 'value', valueField: 'value', list: mainFactoryList.wxjb },

			{ type: "SELECT", label: "维修类别", field: "leibie", initialValue: data.leibie },
			{ type: "SELECT", label: "紧急程度", field: "jinji", initialValue: data.jinji, name: 'value', valueField: 'value', list: mainFactoryList.jinji },
			{ type: "CHECKBOX", label: "是否停机", field: "harborTwoHundredPrice", initialValue: data.harborTwoHundredPrice },
			{ type: "INPUTNUMBER", label: "停机时长", field: "remarks", initialValue: data.remarks },
			{ type: "DATE", label: "开始时间", field: "startTime", initialValue: data.harborMinimumPrice },
			{ type: "DATE", label: "结束时间", field: "endTime", initialValue: data.harborMinimumPrice },
			{ type: "INPUT", label: "维修用时", field: "useTime", initialValue: data.harborMinimumPrice },
			{ type: "INPUTNUMBER", label: "维修费用", field: "wxfy", initialValue: data.wxfy },
			{ type: "SELECT", label: "外委单位", field: "wwdw", initialValue: data.wwdw },
			{ type: "INPUT", label: "经验代码", field: "wwdw", initialValue: data.wwdw },
			{ type: "TEXTAREA", label: "工作描述", field: "workmiaosu", initialValue: data.workmiaosu },

			{ type: "TITLE", label: "维修工作量", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "BOTTOM", label: "增加人员", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TABLE", label: "", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TITLE", label: "更换备件", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
			{ type: "TABLE", label: "", field: "harborMinimumPrice", initialValue: data.harborMinimumPrice },
		];
		return drawerFormList;
	};

	// 提交modal
	handleSubmit = data => {
		const { dataSource, chooseData } = this.state;
		let key = chooseData.key;
		let newDataSource = dataSource;
		let index = newDataSource.findIndex((value) => value.key == key);
		if (key) {
			console.log("******修改******")
			for (let j of newDataSource) {
				if (j.key == key) {
					newDataSource[index] = { ...newDataSource[index], ...data }
				}
			}
		} else {
			console.log("******添加******")
			newDataSource.push(data);
		}
		this.setState({
			dataSource: newDataSource,
		})
		this.onClose();


		// 注释
		// const id = this.state.chooseData && this.state.chooseData.id;
		// if (id) {
		// 	data = Object.assign({}, data, { id: id });
		// 	data.updateId = localStorage.getItem('userId');
		// } else {
		// 	data.createId = localStorage.getItem('userId');
		// }
		// this.post('/airCargo/addAirCargo', { data }).then(res => {
		// 	this.success();
		// 	this.fetch({ ...this.state.formValues });
		// 	this.onClose();
		// })

	};

	// 打开modal，判断是修改还是新增 0新增 1修改
	handleModal = (type, data) => {
		if (type) {
			this.setState({
				drawerTitle: "修改",
				drawerVisible: true,
				chooseData: data
			});
		} else {
			this.setState({
				drawerTitle: "新增",
				drawerVisible: true,
			});
		}
	};


	onClose = () => {
		this.setState({
			drawerVisible: false,
			chooseData: {}
		});
		this.modalRef.props.form.resetFields();
	}


	render() {
		const columns = [
			{
				title: '操作', width: 150, dataIndex: 'detail',fixed:'left',
				render: (text, record) => {
					return <span><a href onClick={() =>this.props.history.push('/DetailMaintenanceRecords/'+record.id)}>详细</a></span>
				}
			},
			{ title: '维修单号', width: 150, dataIndex: 'repairOrderNum', fixed:'left'},
			{ title: '设备编号', width: 150, dataIndex: 'equipmentNum',fixed:'left' },
			{ title: '设备名称', width: 150, dataIndex: 'equipmentName',fixed:'left' },
			{ title: '规格型号', width: 150, dataIndex: 'specificationAndModule',fixed:'left' },
			{ title: '使用部门', width: 150, dataIndex: 'dept', },
			{ title: '设备位置', width: 150, dataIndex: 'equipmentLocation', },
			// { title: '部位', width: 100, dataIndex: 'remarks', },
			{ title: '设备类型', width: 100, dataIndex: 'equipmentTypeName', },
			// { title: '申请人', width: 150, dataIndex: 'applicant', },
			{ title: '报修时间', width: 150, dataIndex: 'repairTime', },
			{ title: '维修开始时间', width: 150, dataIndex: 'maintenanceStartTime', },
			{ title: '维修结束时间', width: 150, dataIndex: 'maintenanceEndTime', },
			{ title: '维修用时(小时)', width: 150, dataIndex: 'maintenanceTime', },
			{ title: '停机时间(小时)', width: 150, dataIndex: 'downtime', },
			{ title: '维修费用', width: 100, dataIndex: 'maintenanceCosts', },
			// { title: '备件费用', width: 150, dataIndex: 'bjfy', },
			{ title: '维修级别', width: 150, dataIndex: 'maintenanceLevelName', },
			{ title: '故障原因', width: 150, dataIndex: 'faultReasonName', },
			{ title: '维修组', width: 100, dataIndex: 'teamName', },
			{ title: '维修人员', width: 100, dataIndex: 'majorStaff', },
			// { title: '辅修人员', width: 100, dataIndex: 'minorStaff', },
			// { title: '验证人', width: 100, dataIndex: 'remark4s', },//wu
			{ title: '外委单位', width: 100, dataIndex: 'outsourcingName', },
			{ title: '故障描述', width: 150, dataIndex: 'faultDescription', },
			{ title: '工作描述', width: 150, dataIndex: 'workDescription', },
			{ title: '故障类别', width: 100, dataIndex: 'faultTypeName', },
			// { title: '评分', width: 100, dataIndex: 'sore', },
			{ title: '维修类别', width: 100, dataIndex: 'maintenanceCategoryName', },
			{ title: '紧急程度', width: 100, dataIndex: 'urgencyName', },
			// {
			// 	title: '操作', width: 150,
			// 	render: (text, record) => {
			// 		return <span><a href onClick={() => this.handleModal(1, record)}>修改</a></span>
			// 	}
			// }
		];

		const { chooseData, drawerVisible, drawerTitle, dataSource, loading, total, formValues, selectedData, selectedKeys } = this.state;

		const drawerProps = {
			onRef: (ref) => this.modalRef = ref, visible: drawerVisible, width: 700, drawerFormList: this.drawerFormList(chooseData),
			submit: this.handleSubmit, onClose: this.onClose, title: drawerTitle
		}
		//选择框
		const rowSelection = {
			selectedRowKeys: selectedKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					selectedData: selectedRows,
					selectedKeys: selectedRowKeys
				})
			},
			getCheckboxProps: record => ({
				disabled: record.name === 'Disabled User',
				name: record.name
			})
		};

		return (
			<div className="shadow-radius">
				<Card><BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={(ref) => this.child = ref} /></Card>

				<Tabs tabBarExtraContent={
					<div className="buttonList">
						{/* <Button icon="plus" onClick={() => this.handleModal(0, {})} type="primary"> 添加计划</Button> */}
						{/* <Button icon="edit" onClick={() => this.handleModal(0, {})} type="primary"> 调整计划执行时间</Button> */}
						{/* <Button icon="form" onClick={() => this.handleModal(0, {})} type="primary"> 执行计划</Button> */}
						{/* <Button icon="apartment" onClick={() => this.handleModal(0, {})} type="primary"> 派工</Button> */}
						{/* <Button icon="delete" onClick={() => this.handleModal(0, {})} type="primary"> 删除</Button> */}
						<BasicConfirm title="确认删除?" api={1} icon="delete" button={true} buttonName="删除" data={selectedData} handleConfirm={this.handleConfirm} />
						{/* <FileDown fileName='设备台账模板' buttonName='模板下载' apiPath='/airCargo/carrierPriceExcel'/> */}
						<FileDown fileName='维修记录清单' buttonName='导出' method='post' apiPath={euqApplicationName + '/equipmentMaintenanceRecord/exportEquipmentMaintenanceRecordListExcel'} data={{...this.state.formValues,ids:selectedKeys}} />
						{/* <Button icon="delete" onClick={() => this.handlePrinting(0, {})} type="primary">{' '} 打印</Button> */}
					</div>
				}>
					<TabPane tab='维修记录' key='1'>
						<Table columns={columns} rowSelection={rowSelection} rowKey={(record, index) => record.id} dataSource={dataSource} pagination={false} loading={loading} scroll={{ x: 1300,y:1200 }} />
						<Paging total={total} formValues={formValues} fetch={(pager) => this.fetch(pager)} />
					</TabPane>
				</Tabs>


				<BasicDrawers	{...drawerProps} />

			</div>
		);
	}
}
export default Form.create()(withRouter(App));